﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Runtime.CompilerServices;

namespace Framework.MiddlewareHelp.MiddlewareHelps
{
    public static class ExceptionMiddleware
    {
        /// <summary>
        /// 自定义异常处理
        /// </summary>
        /// <param name="application"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseExceptionHandlerService(this IApplicationBuilder application, Action<IApplicationBuilder> action = null)
        {
            if (action != null)
            {
                return application.UseExceptionHandler(action);
            }
            else
            {
                return application.UseExceptionHandler(x =>
                {
                    x.Run(async y =>
                    {
                        y.Response.StatusCode = 500;
                        await y.Response.WriteAsync("服务异常，请稍后再试。");
                    });
                });
            }
        }
    }
}
